/// <reference path="../../../../assets/js-plugin/core.js" />  
(function () {
	var $tbody = $("#list-body"),
		$searchForm = $("#search-form"),
		$editForm = $("#edit-form"),
		$accountForm = $("#account-form"),
		$exportBtn=$("#exportCompany");
		$addForm = $("#add-form");
	var trHtml = undefined,
		curPage = 1;
		curPage1 = 1;
    var _this = {
    	list : function(params){
    		var params = $searchForm.serializeObject();
			params = params || {};
			params.page = curPage;
			params.size = 10;
    		App.ajax({
    			type:"post",
    			dataType:"JSON",
                data: params,
                resUrl: "http://10.20.0.39:8080/api/v2/boss/customer/list",
                callback: function (rb) {
                    if(rb.code != 1000) return;
                    $tbody.empty();
                    $.each(rb.data.list||[], function(i, d){
                    	var $tr = $(trHtml);
                    	d.contractStartDate = d.contractStartDate.substr(0,10);
                    	d.contractEndDate = d.contractEndDate.substr(0,10);
                    	$tr.setHtml(d).data(d);
                    	_this.initDisabled($tr, d.disabled);
                    	_this.initContractEndDate($tr, d.contractEndDate, d.contractStatus);
						$tr.attr({id:"tr_customer_"+d.id});
                    	$tbody.append($tr);
                    });

					require(['laypage'], function (laypage) {
						var data = rb.data || {};
						laypage({
							cont: 'page-body', //容器。值支持id名、原生dom对象，jquery对象。【如该容器为】：<div id="page1"></div>
							pages:data.totalPage, //通过后台拿到的总页数
							curr: data.pageNumber || 1, //当前页
							jump: function (obj, first) { //触发分页后的回调
								curPage = obj.curr;
								if (!first) {
									_this.list();
								}
							}
						});
					});
                }
    		});
    	},
    	accountsList : function(){
    		var params = $editForm.serializeObject();
			params = params || {};
			params.page = curPage1;
			params.size = 10;
			params = $.extend({}, params);
			App.ajax({
				data: params,
				resUrl: "ygxStudent/list",
				callback: function(rb) {
					if(!rb.status) return;
					var rbData = rb.data;
					$("#stlist-body").empty().show();
					$.each(rbData.list || [], function(i, d) {
						var $tr = $(sttrHtml);
						d.num = i + 1;
						$tr.setHtml(d).data(d);
						$tr.find("span").data("id", d.id);
						$("#stlist-body").append($tr);
						$('td').css('text-align', 'center');
					});
					require(['laypage'], function(laypage) {
						laypage({
							cont: 'stpage-body', //容器。值支持id名、原生dom对象，jquery对象。【如该容器为】：<div id="page1"></div>
							pages: rbData.totalPage, //通过后台拿到的总页数
							curr: rbData.pageNumber || 1, //当前页
							jump: function(obj, first) { //触发分页后的回调
								curPage1 = obj.curr;
								if(!first) {
									_this.accountsList();
								}
							}
						});
					});
				}
			});
    	},
    	initDisabled : function($tr, disabled){
			if(disabled==2){
				$tr.find("[label-disabled]").html('<span class="label label-success">正常</span>');
				$tr.find("[btn-type=disabled]").addClass("am-text-danger").removeClass("am-text-secondary").html('<span class="am-icon-toggle-off"></span> 禁用');
				$tr.find("[btn-type=edit]").removeAttr("disabled");
			}else{
				$tr.find("[label-disabled]").html('<span class="label label-danger">已禁用</span>');
				$tr.find("[btn-type=disabled]").addClass("am-text-secondary").removeClass("am-text-danger").html('<span class="am-icon-toggle-on"></span> 启用');
				$tr.find("[btn-type=edit]").attr("disabled", "disabled");
			}
    	},
    	initContractEndDate : function($tr, contractEndDate, contractStatus){
    		$tr.find("[label-contractEndDate]").html('<span class="lable">'+ contractEndDate +'</span>');
    		if(contractStatus == 1){
    			$tr.find("[label-contractEndDate]>span").addClass("label-danger").removeClass("label-success").removeClass("label-warning");
    		} else if(contractStatus == 2){
    			$tr.find("[label-contractEndDate]>span").addClass("label-warning").removeClass("label-success").removeClass("label-danger");
    		} else {
    			$tr.find("[label-contractEndDate]>span").addClass("label-success").removeClass("label-danger").removeClass("label-warning");
    		}
    	},
    	initSelect2: function(eleId, url, mId, mText){
    		$(eleId).select2({
    			minimumInputLength : 0,
    			allowClear : true,
    			placeholder : {id: mId, text: mText},
    			ajax : {
    				url : url,
    				cache : false,
    				dataType : 'json',
    				data : function(term) {
    					return {
    						text : term
    					};
    				},
    				results : function(data) {
    					return {
    						results : data.data, 
    						more: false
    					};
    				},
    				
    				processResults: function(data) {
						initSelect2InputLengthLimit();
						return {
							results: data.results,
						};
					}
    			}
    		});
    		$(eleId).select2("data", {"id": mId, "text": mText });
    	},
		submitForm: function(opt){
			if(opt.type=="close"){
				App.closeEntitySlider();
				return;
			}
			var $form = opt.selector;
			var data = opt.data || {};
			var type = opt.type;
			var cb = opt.cb || function(){};

			var postData = $form.serializeObject();
			postData = $.extend({}, data, postData);

			if(!postData.customerName){
				layer.msg('请填写客户名称', {icon: 2});
				return false;
			}
			if(!postData.contactPerson){
				layer.msg('请填写联系人', {icon: 2});
				return false;
			}
			if(!postData.contactPhone){
				layer.msg('请填写联系电话', {icon: 2});
				return false;
			}
			if(!(/^1[34578]\d{9}$/.test(postData.contactPhone))){
				layer.msg('联系电话格式不正确', {icon: 2});
				return false;
			}
			if(!postData.businessLicense){
				layer.msg('请填写营业执照号', {icon: 2});
				return false;
			}
			if(!(/^[0-9a-zA-Z]*$/.test(postData.businessLicense))){
				layer.msg('营业执照号只允许数字和字母', {icon: 2});
				return false;
			}
			if(!postData.customerType){
				layer.msg('请填写客户类别', {icon: 2});
				return false;
			}
			if(!postData.contractStartDate){
				layer.msg('请填写合同起始日期', {icon: 2});
				return false;
			}
			if(!postData.contractEndDate){
				layer.msg('请填写合同截止日期', {icon: 2});
				return false;
			}
			var _data = {};
			
			$.each(postData, function(k,v){
				if(k == 'contractStartDate' || k == 'contractEndDate' || k == 'disableTime'){
					v = App.strToDate(v);
				}
				_data[k] = v;
			});
			var url;
			if(type == 'add'){
				url = "http://10.20.0.39:8080/api/v2/boss/customer/add";
			}else if(type == 'edit'){
				url = "http://10.20.0.39:8080/api/v2/boss/customer/update";
				delete _data.disableTime;
			}
			App.ajax({
				data: _data,
				resUrl: url,
				callback: function (rb) {
					if(rb.code != 1000){
						layer.msg(rb.msg||'操作不成功', {icon: 5});
						return;
					}
					layer.msg('成功', {icon: 1});
					_this.list();
					!!cb && cb();
				}
			});
		},
//		xinzengAccounts : function(){
//			var html = $("#xinzengAccounts").html();
//			var $st = $(html);
//			layer.confirm($st[0].outerHTML, {
//				type: 0,
//				title: "新增帐号",
//				closeBtn: 0,
//				area: ['600px', '380px'], //宽高
//				btn: ['确定', '取消'] //按钮
//			}, function() {
//				var $div = $("#alter-status-div");
//				var stName = $div.find("[name=stationName]").val();
//				var stTime = $div.find("[name=startTimestart]").val();
//				var stOrder = $div.find("[name=stOrder]").val();
//				if(!stName) {
//					layer.msg('请填写站点名称!', {
//						type: 1
//					});
//					return;
//				}
//				if(!stOrder) {
//					layer.msg('请填写站点顺序!', {
//						type: 1
//					});
//					return;
//				}
//				App.ajax({
//					data: {
//						lineId: lineId,
//						stationId: stName,
//						arriveTime: stTime,
//						sequence: stOrder
//					},
//					resUrl: "ygxLineStation/add",
//					callback: function(rb) {
//						if(rb.code == 0) {
//							layer.msg('成功', {
//								icon: 1
//							});
//							_this.accountsList(lineId);
//						} else {
//							layer.msg(rb.msg || '失败', {
//								icon: 5
//							});
//							var _index = layer.confirm('<div style="margin: auto;width: 222px;height:80px;font-size:18px;line-height:80px;text-align:center;">' + rb.msg + '</div>', {
//								type: 1,
//								title: "",
//								area: ['300px', 'auto'], //宽高
//								btn: ['确定']
//							}, function() {
//								layer.close(_index);
//							});
//						}
//					}
//				});
//			}, function() {
//				layer.msg('操作已取消', {
//					icon: 7
//				});
//			});
//		},
    	initEvent : function(){
    		App.ajax({
    			data:{type:'客户类别'},
    			type:'get',
	    		resUrl: "http://10.20.0.39:8080/api/v2/boss/dictionary/get/type",
	    		callback:function(rb){
	    		 	if(rb){
	    		 		var opt='';
	    		 		$.each(rb, function(i,d) {
	    		 			opt="<option value='"+d.value+"'>"+d.text+"</option>";
	    		 			$searchForm.find("[name=customerType]").append(opt);
	    		 			$addForm.find("[name=customerType]").append(opt);
	    		 		});
	    		 	}
	    		}
    		});
    		$("#AddCustomerManager").select2({
				placeholder: "请选择客户 ",
				minimumInputLength: 0,
				allowClear: true,
				ajax: {
					url: 'http://10.20.0.39:8080/api/v2/boss/customer/manager',
					dataType: 'json',
					data: function(term, page) {
						return {
							text: term
						};
					},
					results: function(data, page) {
						return {
							results: data.data
						};
					},
					processResults: function(data, params) {
						params.page = params.page || 1;

						return {
							results: data.results,
							pagination: {
								more: (params.page * 10) < data.count_filtered
							}
						};
					}
				}
			});
    		$("#startDate").dateRangePicker({
    			autoClose: false,
				singleDate: true,
				timePicker: false,
				startOfWeek: 'Wednesday',
				format: 'YYYY-MM-DD',
				time: {
					enabled: false 
				}, 
				callback: function(){
               		if( _this.dayDiff( $("#startDate").val().split(' ')[0] , $("#endDate").val().split(' ')[0] ) <= 0 ){
               			$("#endDate").val('');
               		}
               		if( $("#startDate").val().split(' ')[0] != '' ){
	               		var startTime = $("#startDate").val().split(' ')[0];
	               		$("#endDate").dateRangePicker(
							{
								startDate: startTime,
			    				endDate: '2020-12-31',
								autoClose: false,
								singleDate: true,
								timePicker : false,
								startOfWeek: 'Wednesday',
								format:'YYYY-MM-DD',
								time: {
				                    enabled: false
				               },
				               callback: function(){
				               }
							}
						);
               		}
               	}
			});
			$("#endDate").dateRangePicker(
				{
					autoClose: false,
					singleDate: true,
					timePicker : false,
					startOfWeek: 'Wednesday',
					format:'YYYY-MM-DD',
					time: {
	                    enabled: false
	               	},
	               	callback: function(){
	                }
				}
			);
    		$("#addstartDate").dateRangePicker({
    			autoClose: false,
				singleDate: true,
				timePicker: false,
				startOfWeek: 'Wednesday',
				format: 'YYYY-MM-DD',
				time: {
					enabled: false 
				}, 
				callback: function(){
               		if( _this.dayDiff( $("#addstartDate").val().split(' ')[0] , $("#addendDate").val().split(' ')[0] ) <= 0 ){
               			$("#addendDate").val('');
               		}
               		if( $("#addstartDate").val().split(' ')[0] != '' ){
	               		var startTime = $("#addstartDate").val().split(' ')[0];
	               		$("#addendDate").dateRangePicker(
							{
								startDate: startTime,
			    				endDate: '2020-12-31',
								autoClose: false,
								singleDate: true,
								timePicker : false,
								startOfWeek: 'Wednesday',
								format:'YYYY-MM-DD',
								time: {
				                    enabled: false
				               },
				               callback: function(){
				               }
							}
						);
               		}
               	}
			});
			$("#addendDate").dateRangePicker(
				{
					autoClose: false,
					singleDate: true,
					timePicker : false,
					startOfWeek: 'Wednesday',
					format:'YYYY-MM-DD',
					time: {
	                    enabled: false
	               	},
	               	callback: function(){
	                }
				}
			);
//			$editForm.submit(function(){
//				var params = $editForm.serializeObject();
//				curPage1 = 1;
//				_this.accountsList(params);
//				return false;
//			});
			$searchForm.submit(function(){
				var params = $searchForm.serializeObject();
				curPage = 1;
				_this.list(params);
				return false;
			});
			$addForm.submit(function(){
				var $form = $addForm;
				_this.submitForm({
					selector: $form,
					type: "add",
					cb: function(){
						$('#add-div').slideToggle();
					}
				});
				return false;
			});
			$exportBtn.click(function() {
				var _data = $searchForm.serializeObject();
				var timeRange = _data.createDt || "";
				var param ="?";
				$.each(_data, function(k,v){
					param += "com." + k+"="+v+"&";
				});
				window.open("/stat/companyExport"+param);
			});

			$addForm.find("[name=name]").change(function(){
				$addForm.find("[name=qiYeDaiMa],[name=qiYeShengYunZhengID]").val("");
			});

			// 编辑
			App.delegate({
			    btntype: "[btn-type=edit]",
			    callback: function (data) {  	
					var opt = {
						content: $("#eform").html(),
						submitBtn: "[hy-type-submit]",//可选默认已经是hy-type-submit。可以不加
						submit: function () {
							_this.submitForm({
								selector: $("#edit-form"),
								type: "edit",
								data: data,
								cb: function(){
								    App.closeEntitySlider();
								}
							});
						},
						callback: function (e) {
							var $form = $(e);
							$form.find("#query").click(function(){
								_this.highwayQuery($form);
							});
							//  编辑时间联动  begin
							$("#editStartDate").dateRangePicker({
				    			autoClose: false,
								singleDate: true,
								timePicker: false,
								startOfWeek: 'Wednesday',
								format: 'YYYY-MM-DD',
								time: {
									enabled: false 
								}, 
								callback: function(){
				               		if( _this.dayDiff( $("#editStartDate").val().split(' ')[0] , $("#editEndDate").val().split(' ')[0] ) <= 0 ){
				               			$("#editEndDate").val('');
				               		}
				               		if( $("#editStartDate").val().split(' ')[0] != '' ){
					               		var startTime = $("#editStartDate").val().split(' ')[0];
					               		$("#editEndDate").dateRangePicker(
											{
												startDate: startTime,
							    				endDate: '2020-12-31',
												autoClose: false,
												singleDate: true,
												timePicker : false,
												startOfWeek: 'Wednesday',
												format:'YYYY-MM-DD',
												time: {
								                    enabled: false
								               },
								               callback: function(){
								               }
											}
										);
				               		}
				               	}
							});
							$("#editEndDate").dateRangePicker(
								{
									autoClose: false,
									singleDate: true,
									timePicker : false,
									startOfWeek: 'Wednesday',
									format:'YYYY-MM-DD',
									time: {
					                    enabled: false
					               	},
					               	callback: function(){
					                }
								}
							);
							// 编辑时间联动 end
							App.ajax({
				    			data:{type:'客户类别'},
				    			type:'get',
					    		resUrl: "http://10.20.0.39:8080/api/v2/boss/dictionary/get/type",
					    		callback:function(rb){
					    		 	if(rb){
					    		 		var opt='';
					    		 		$.each(rb, function(i,d) {
					    		 			opt="<option value='"+d.value+"'>"+d.text+"</option>";
					    		 			$("#editCustomerType").append(opt);
					    		 		});
					    		 		data.customerType = data.customerTypeId;
					    		 		data.customerManager = data.customerManagerId;
					    		 		App.setFormData($form, data);
					    		 	}
					    		}
				    		});
							_this.initSelect2("#editCustomerManager", "http://10.20.0.39:8080/api/v2/boss/customer/manager",data.customerManagerId ,data.customerManager );	
						}
					}
					App.drawDetailPanel(opt);
				}
			});
			// 更多
			App.delegate({
			    btntype: "[btn-type=details]",
			    callback: function (data) {  	
					var opt = {
						content: $("#detailsform").html(),
						submitBtn: "[hy-type-submit]",//可选默认已经是hy-type-submit。可以不加
						submit: function () {
							_this.submitForm({
								selector: $("#moredit-form"),
								type: "close",
								data: data,
								cb: function(){
								    App.closeEntitySlider();
								}
							});
						},
						callback: function (e) {
							App.ajax({
								data: {id: data.id},
								type: "get",
								resUrl: "http://10.20.0.39:8080/api/v2/boss/customer/get",
								callback: function(rb){
									if(rb){
										data.disableTime = rb.data.disableTime;
										App.setFormData($form, data);
									}
								}
							});
							$("#entitySlider .detail-brand").find("vl").html("更多");
							var $form = $(e);
							$form.find("#query").click(function(){
								_this.highwayQuery($form);
							});
						}
					}
					App.drawDetailPanel(opt);
				}
			});
			// 账号管理 未完成
			App.delegate({
				btntype: "[btn-type='set']",
				callback: function(data) {
					var lineId = data.id;
					var opt = {
						content: $("#accountform").html(),
						submit: function(from) {
							App.closeEntitySlider();
						},
						callback: function(e) {
							$("#entitySlider .detail-brand").find("vl").html("帐号管理");
							sttrHtml = $("#stlist-body").html();
							var $form = $(e);
							$("body").undelegate('[btn-type=xinzengAccounts]', 'click');
							$("body").delegate("[btn-type=xinzengAccounts]", 'click', function() {
								_this.xinzengAccounts($(this).data().id);
							});
							$("#accountSearch").on('click',function(){
								var params = $editForm.serializeObject();
								curPage1 = 1;
								_this.accountsList(params);
								return false;
							})
							_this.accountsList(lineId);
						}
					};
					App.drawDetailPanel(opt);
				}
			});
			// 禁用or启用
			App.delegate({
			    btntype: "[btn-type=disabled]",
			    callback: function (data, $tr) {
			    	var disabled = data.disabled;
			    	var url;
			    	if(disabled == 1){
			    		url = "http://10.20.0.39:8080/api/v2/boss/customer/enable"
			    	}else{
			    		url = "http://10.20.0.39:8080/api/v2/boss/customer/disable"
			    	}
					var postData = { id: data.id };
					App.ajax({
						data: postData,
						resUrl: url,
//						resUrl: "http://10.20.0.39:8080/api/v2/boss/customer/disable",
						callback: function (rb) {
							if (rb.code != 1000) {
								layer.msg(rb.msg||'操作不成功', { icon: 5 });
								return;
							}
							layer.msg('成功', { icon: 1 });
//							data.status = status;
							if(disabled == 1){
								disabled = 2;
							}else{
								disabled = 1;
							}
							data.disabled = disabled;
							$tr.data(data);
								
							_this.initDisabled($tr, disabled);

						}
					});
				}
			});
			// 删除 
			App.delegate({
			    btntype: "[btn-type=delete]",
			    callback: function (data, $tr) {
			    	var msg = '确认删除？';
			    	var btnok = '确认';
			    	var _index = layer.confirm('<div style="margin: auto;width: 222px;height:80px;font-size:18px;line-height:80px;text-align:center;">' + msg + '</div>', {
						type: 1,
						title: "",
						area: ['300px', 'auto'], //宽高
						btn: [btnok, '再考虑下']
					}, function(){
						App.ajax({
							data: {id: data.id},
							resUrl: "http://10.20.0.39:8080/api/v2/boss/customer/delete",
							callback: function (rb) {
								if (rb.code != 1000 ) {
									layer.msg(rb.msg||'操作不成功', { icon: 5 });
									return;
								}
								layer.msg('成功', { icon: 1 });
								_this.list();
								layer.close(_index);
							}
						});
					}, function (){
						layer.close(_index);
					});
				}
			});

			$("#add-form [id='area']").change(function(){
				var area = $(this).val();
				console.log("["+area+"]&&&");
				$("#add-form [name='code']").inputmask("[\\"+area+"]&&&");
			});
			$("#add-form [name='code']").inputmask("[B]&&&");
    	},
    	 /**
		 * 两个日期的天数差，参数格式：'YYYY-MM-DD HH:mm:ss'
		 * @param {Object} startDate 开始日期	
		 * @param {Object} endDate 结束日期
		 */
		dayDiff: function( startDate, endDate ){
			var beginTime = startDate;
			var endTime = endDate;
			var beginDate = new Date(beginTime);
			var endDate = new Date(endTime);
			var day = (endDate.getTime() - beginDate.getTime() ) / ( 24*60*60*1000 ) + 1;
			return day;
		},
    	parse : function(){
    		trHtml = $tbody.html();
    		$tbody.empty().show();
    	},
        init : function () {
        	_this.parse();
        	_this.initEvent();
        	_this.list();
			laydate.skin('molv');
        }
    }
    _this.init(); //页面初始化入口设置
})();
